package com.wkn.wknAdmin.config.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.wkn.wknAdmin.entity.User;
import com.wkn.wknAdmin.exception.APIException;
import com.wkn.wknAdmin.result.ResultCode;
import com.wkn.wknAdmin.service.UserService;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Title:
 * @Description:
 * @Author: WKN
 * CreateDate: 2022/8/13 2:08
 */

public class JwtInterceptor implements HandlerInterceptor {


    @Resource
    private UserService userService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String token = request.getHeader("token");

        // 如果不是映射到方法直接通过   确保所以请求在方法上可以不写
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 执行认证
        if (token == null) {
            throw new APIException(ResultCode.NO_TOKEN);
        }


        // 获取 token 中的 user id
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new APIException(ResultCode.TOKEN_IS_INVALID);
        }


        // 根据token中的userId查询数据库
        User user = userService.getById(userId);
        if (user == null) {
            throw new APIException(ResultCode.USER_NOT_EXIST);
        }



        // 用户密码加签 验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new APIException(ResultCode.TOKEN_FAILED);
        }
        return true;

    }
}
